import Mock from "mockjs";

function param20bj (url) {
    const search = url.split('?')[1]
    if (!search) {
        return {}
    }
    return JSON.parse(
        '{"' +
        decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')+
        '"}'
    )
}

let List = []
const count = 30

for (let i = 0; i < count; i++){
    List.push(
        Mock.mock({
            id: Mock.Random.guid(),
            name: Mock.Random.cname(),
            account: Mock.Random.integer(100000, 999999),
            password: Mock.Random.integer(100000, 999999)
        }))
}

export default {
    // 获取列表，参数：name, page, limit
    getUserList: config => {
        const { name, page = 1, limit = 20} = param20bj(config.url)
        const mockList = List.filter(user => {
            if (name && user.name.indexOf(name) === -1) return false
            return true
        })
        const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))
        return {
            code: 200,
            count: mockList.length,
            list: pageList
        }
    },

    // 增加用户
    createUser: config => {
        const { name, account, password } = JSON.parse(config.body)
        List.unshift({
            id: Mock.Random.guid(),
            name: name,
            account: account,
            password: password
        })
        return {
            code: 200,
            data: {
                message: '添加成功'
            }
        }
    },

    // 修改用户
    editUser: config => {
        const { id, name, account, password } = JSON.parse(config.body)
        List.some(item => {
            if (item.id == id) {
                item.name = name
                item.account = account
                item.password = password
                return true;
            }
            return false;
        })
        return {
            code: 200,
            data: {
                message: '编辑成功'
            }
        }
    },

    // 删除用户
    deleteUser: config => {
        const { id } = JSON.parse(config.body)
        if (!id){
            return {
                code: -999,
                data: {
                    message: '删除失败，id参数不正确'
                }
            }
        } else {
            List = List.filter(item => item.id !== id)
            return {
                code: 200,
                message: '删除成功'
            }
        }
    }
}

